package service

import (
	"context"

	"Data-API-MCP/backend/internal/domain/entity"
	"Data-API-MCP/backend/internal/domain/repository"
	"errors"
)

// ConnectionService 数据库连接领域服务
type ConnectionService struct {
	connectionRepo repository.ConnectionRepository
}

// NewConnectionService 创建连接服务
func NewConnectionService(connectionRepo repository.ConnectionRepository) *ConnectionService {
	return &ConnectionService{
		connectionRepo: connectionRepo,
	}
}

// CreateConnection 创建连接
func (s *ConnectionService) CreateConnection(ctx context.Context, connection *entity.Connection) error {
	// 检查连接名称是否已存在
	if _, err := s.connectionRepo.FindByName(ctx, connection.Name); err == nil {
		return errors.New("连接名称已存在")
	}

	// 测试连接
	if err := s.connectionRepo.TestConnection(ctx, connection); err != nil {
		return errors.New("连接测试失败: " + err.Error())
	}

	return s.connectionRepo.Create(ctx, connection)
}

// UpdateConnection 更新连接
func (s *ConnectionService) UpdateConnection(ctx context.Context, connection *entity.Connection) error {
	// 检查连接是否存在
	if _, err := s.connectionRepo.FindByID(ctx, connection.ID); err != nil {
		return errors.New("连接不存在")
	}

	// 测试连接
	if err := s.connectionRepo.TestConnection(ctx, connection); err != nil {
		return errors.New("连接测试失败: " + err.Error())
	}

	return s.connectionRepo.Update(ctx, connection)
}

// DeleteConnection 删除连接
func (s *ConnectionService) DeleteConnection(ctx context.Context, id string) error {
	// 检查连接是否存在
	if _, err := s.connectionRepo.FindByID(ctx, id); err != nil {
		return errors.New("连接不存在")
	}

	return s.connectionRepo.Delete(ctx, id)
}

// GetConnection 获取连接
func (s *ConnectionService) GetConnection(ctx context.Context, id string) (*entity.Connection, error) {
	return s.connectionRepo.FindByID(ctx, id)
}

// GetConnectionList 获取连接列表
func (s *ConnectionService) GetConnectionList(ctx context.Context, offset, limit int) ([]*entity.Connection, error) {
	return s.connectionRepo.List(ctx, offset, limit)
}

// GetConnectionCount 获取连接总数
func (s *ConnectionService) GetConnectionCount(ctx context.Context) (int64, error) {
	return s.connectionRepo.Count(ctx)
}

// GetConnectionListByType 获取指定类型的连接列表
func (s *ConnectionService) GetConnectionListByType(ctx context.Context, dbType string, offset, limit int) ([]*entity.Connection, error) {
	return s.connectionRepo.ListByType(ctx, dbType, offset, limit)
}

// GetConnectionCountByType 获取指定类型的连接总数
func (s *ConnectionService) GetConnectionCountByType(ctx context.Context, dbType string) (int64, error) {
	return s.connectionRepo.CountByType(ctx, dbType)
}

// TestConnection 测试连接
func (s *ConnectionService) TestConnection(ctx context.Context, connection *entity.Connection) error {
	return s.connectionRepo.TestConnection(ctx, connection)
}
